package org.refresh.beanshell;

import org.refresh.core.intelligence.Constraint;
import org.refresh.core.intelligence.ConstraintEvaluationError;
import org.refresh.core.intelligence.ConstraintEvaluator;

import bsh.Interpreter;

/*******************************************************************************
 * Copyright (c) 2005, 2006 Jules White. All rights reserved. This program and
 * the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors: Jules White - initial API and implementation
 ******************************************************************************/
public class BeanShellEvaluator implements ConstraintEvaluator {

	public boolean evaluate(Object src, Object trg, Constraint constraint) {
		Object val = null;

		try {
			Interpreter i = new Interpreter(); 
			i.set("self", src); 
			i.set("target", src);
			val = i.eval(((BeanShellConstraint) constraint).getExpression());
			if (val instanceof Boolean) {
				return ((Boolean) val).booleanValue();
			} else {
				return val != null;
			}
		} catch (Exception e) {
			throw new ConstraintEvaluationError(constraint, e);
		}
	}

}
